#!/bin/bash

show_help() {
  echo -e "do something in vm by qemu-guest-agent."
  echo -e "Usage:"
  echo -e "\tprickvm <instance> <action>"
  echo -e "Parameters:"
  echo -e "\tinstance        valid vm name or id , e.g. instance-000002bb"
  echo -e "\t                run \`virsh list\" to get it."
  echo -e "\taction          can be: \"test\", \"zabbix-stat\", \"nvstat\", \"sshd-nodns\""
}

get_qemu_exec_pid() {
    # {"return":{"pid":2868020}}
    local str="$1"
    echo -e "d=$str\nprint d[\"return\"][\"pid\"]\n" | python -
}

get_qemu_exec_status() {
    # {"return":{"exited":false}}
    local pid=$1
    local max=999
    local status=
    local str=

    while ((max>0)); do
        str=$(virsh qemu-agent-command $inst "{\"execute\":\"guest-exec-status\", \"arguments\":{\"pid\": $pid}}") || return 1
        # workaround for Python
        str=$(echo $str |sed -e 's/:false/:False/' -e 's/:true/:True/')
        status=$(echo -e "d=$str\nprint d[\"return\"][\"exited\"]\n" | python -)
        if [ "$status" == "False" ];then 
            ((max--))
            if ((max>0)); then
               sleep 1
               continue
            else
               return 2
            fi
        fi
        if [ "$status" == "True" ];then
            # {"return":{"exitcode":0,"err-data":"BASE64DATA","out-data":"BASE64DATA","exited":True}}
            echo -e "import sys\nimport base64\nd=$str\nd=d['return']\nprint \"%s\"%base64.b64decode(d['out-data'])\nsys.exit(d['exitcode'])" | python -
            return $?
        fi
        return 3
    done
}

inst=$1
action=$2

[ -n "$inst" ] || { show_help; exit 1; }
[ -n "$action" ] || { show_help; exit 1; }

if [ "$action" == "zabbix-stat" ]; then 
    ret=$(virsh qemu-agent-command $inst '{"execute":"guest-exec", "arguments":{"path": "/bin/bash", "arg":["-c", "rm -rf ./zabbix-stat/;type git 2>&1 || { type apt 2>&1 && apt install -y git 2>&1; } || { type yum 2>&1 && yum install -y git 2>&1; } && git clone https://gitee.com/wanghuiic/zabbix-stat 2>&1 && pushd zabbix-stat/ && sudo ./install-zabbix-stat.sh 2>&1 && popd && rm -rf ./zabbix-stat/"] , "capture-output":true}}') || exit 2
elif [ "$action" == "nvstat" ]; then 
    ret=$(virsh qemu-agent-command $inst '{"execute":"guest-exec", "arguments":{"path": "/bin/bash", "arg":["-c", "type git 2>&1 || { type apt 2>&1 && apt install -y git 2>&1; } || { type yum 2>&1 && yum install -y git 2>&1; } && git clone https://gitee.com/wanghuiic/nvstat 2>&1 && pushd nvstat/ && tar zxvf dist.tgz && ./install.sh 2>&1 && popd && rm -rf nvstat/ && nvstat"] , "capture-output":true}}') || exit 2
elif [ "$action" == "test" ]; then 
    ret=$(virsh qemu-agent-command $inst '{"execute":"guest-exec", "arguments":{"path": "/bin/bash", "arg":["-c", "echo \"# zabbix-stat\" && zabbix-stat 2>&1; lspci|grep -i nvidia && { echo \"# nvstat\" && nvstat 2>&1; } || true"] , "capture-output":true}}') || exit 2
elif [ "$action" == "sshd-nodns" ]; then 
    ret=$(virsh qemu-agent-command $inst '{"execute":"guest-exec", "arguments":{"path": "/bin/bash", "arg":["-c", "sed -i -e \"/^[[:space:]]*UseDNS/d\" /etc/ssh/sshd_config 2>&1 && echo \"UseDNS no\" >> /etc/ssh/sshd_config && systemctl restart sshd 2>&1 && echo \"UseDNS no\""] , "capture-output":true}}') || exit 2
fi

echo $ret
pid=$(get_qemu_exec_pid $ret)
[ -n "$pid" ] || exit 3
get_qemu_exec_status $pid
